<?php
/*********************************************************************
 * LOCALITY AJAX FILE
 * 
 * Author: hthieu1110
 * Date: 10/04/2011
 **********************************************************************
 * Get the JSON of locality by keyword
 *
 **********************************************************************/
  
require_once dirname(realpath(__FILE__)).'./../../../config/config.inc.php';

#connect to DB
try {
  $Db = new Db();
} catch(Exception $e) {
  return array();
}

#main execution
$keyword = $_GET['keyword'];
$limit = isset($_GET['limit']) ? $_GET['limit'] : MAX_LOCALITY_SUGGESTION;

#convert the speciaux characters
$keyword = htmlspecialchars($keyword, ENT_QUOTES);

#get town
$query = "
  SELECT *
  FROM town
  WHERE name LIKE '%".mysql_escape_string($keyword)."%'
  OR code LIKE '%".mysql_escape_string($keyword)."%'
  LIMIT 0,".$limit;

$towns = $Db->selectTable($query);
$townsCleaned = array();
/*
$results = @mysql_query($query);

if (!$results) return array();

$towns = array();
while ($town = mysql_fetch_array($results)) {
  $towns[] = array('code'=>$town['code'], 'name'=>htmlspecialchars_decode($town['name'], ENT_QUOTES)); // town=array(code=>code, name=>name);
}
*/

foreach($towns as $town) {
  $townsCleaned[] = array('code'=>$town['code'], 'name'=>htmlspecialchars_decode($town['name'], ENT_QUOTES)); // town=array(code=>code, name=>name);
}

$townsJsoned = json_encode($townsCleaned);

echo $townsJsoned;








